package org.libarae.communication.common;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Picture extends Common {
	private BufferedImage mImage;

	public Picture() {
		super();
	}

	public Picture(BufferedImage image) {
		this.mImage = image;
	}

	@Override
	public void createXml(Document doc, Element root) {
		//check to make sure we have an image
		if(mImage == null)
			return;
		
		try {
			// encode the image into something we can put into xml
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(mImage, "png", baos);
			baos.flush();
			// make into string
			Base64 base64 = new Base64();
			String encodedImage = base64.encodeToString(baos.toByteArray());
			baos.close();
			// add node
			Element node = doc.createElement("mImage");
			node.setTextContent(encodedImage);
			root.appendChild(node);
		}
		catch (Exception e) {
			//print the error
			System.err.println("Error converting imgage to xml");
		}
	}

	@Override
	public void decodeXML(Node root) {
		try {
			NodeList nodeList = root.getChildNodes();
			// set all of the nodes in their proper places
			for (int i = 0; i < nodeList.getLength(); i++) {
				String nodeName = nodeList.item(i).getNodeName();
				//get the image
				if (nodeName.equals("mImage")) {
					//decode the image from the xml
					String encodedImage = nodeList.item(i).getTextContent();
					Base64 base64 = new Base64();
					byte[] bytes = base64.decode(encodedImage);
					mImage = ImageIO.read(new ByteArrayInputStream(bytes));
				}
			}
		}
		catch (Exception e) {
			System.err.println("Error converting xml to image");
		}
	}

	public BufferedImage getmImage() {
		return mImage;
	}

	public void setmImage(BufferedImage mImage) {
		this.mImage = mImage;
	}
}
